import api from '../../utils/api'; // 引入api接口管理文件
import customerApi from '../../utils/customerApi';
import {
  throttle2
} from '../../utils/util.js';

const app = getApp()
Component({
  options: {
    addGlobalClass: true,
  },
  lifetimes: {
    created: function () {},

    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  attached: function () {
    if (wx.getStorageSync('userInfo')) {
      this.setData({
        userInfo: wx.getStorageSync('userInfo')
      })
    }
    if (wx.getStorageSync('bindMobile')) {
      this.setData({
        bindMobile: wx.getStorageSync('bindMobile')
      })
    } else {
      this.setData({
        bindMobile: false
      })
    }
    this.getProtocolUrl();
  },
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    userInfo: {},
    userPhone: '',
    bindMobile: true,
    isFreeze: true,
    privacyUrl: '',
    serviceUrl: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getProtocolUrl() {
      api.getProtocolUrl({
        success: (res) => {
          console.log('res: ', res);
          if (+res.code === 0) {
            this.setData({
              privacyUrl: res.data.privacyUrl,
              serviceUrl: res.data.serviceUrl
            })
          }
        }
      })
    },
    getUserInfoBythrottle2: throttle2((that) => {
      wx.clearStorageSync()
      wx.getUserProfile({
        desc: '获取你的昵称、头像', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          let userInfo = res.userInfo
          wx.setStorageSync('userInfo', userInfo)
          that.setData({
            userInfo: userInfo
          }, () => {
            that.login(true)
          })
        }
      })
    }, 2000),
    getUserInfo() {
      this.getUserInfoBythrottle2(this);
    },
    login(isShow) {
      const that = this
      wx.login({
        success(res) {
          if (res.code) {
            const {
              channel
            } = app.globalData || {}
            console.log('app.globalData: ', app.globalData);
            isShow && wx.showLoading({
              title: '登录中...',
              mask: true,
            })
            api.commonOauth({ // 调用接口，传入参数
              data: {
                serviceid: 'wxff3fc00494f4f0e3',
                loginType: 'WeChatApp',
                code: res.code,
                ...(+channel ? {
                  fromWhere: +channel
                } : {})
              },
              success: data => {
                isShow && wx.hideLoading()
                if (data.subCode === 10001) {
                  that.register()
                } else if (data.subCode === 10005) {
                  wx.showToast({
                    title: '您的账号已被冻结',
                    icon: 'none'
                  })
                  that.setData({
                    isFreeze: true
                  })
                } else {
                  that.setData({
                    isFreeze: false
                  })
                  wx.setStorageSync('token', data.data.token)
                  wx.setStorageSync('imuid', data.data.imuid)
                  that.bindCheckBindMobile()
                  channel && that.messageCompanyData(channel); // 携带channel 才调用
                }
              },
              fail: err => {
                isShow && wx.hideLoading()
              }
            })
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
    },
    register() {
      const that = this
      wx.showLoading({
        title: '注册中...',
        mask: true
      })
      wx.login({
        success(res) {
          api.userRegister({ // 调用接口，传入参数
            data: {
              serviceid: 'wxff3fc00494f4f0e3',
              code: res.code,
              registerType: 2,
              userType: 1,
              ...that.data.userInfo
            },
            success: resdata => {
              wx.hideLoading()
              if (resdata.code * 1 === 0) {
                that.login()
              } else {
                wx.showToast({
                  title: resdata.msg,
                  icon: 'none'
                })
              }
              // getApp().global.openid = resdata.data.openid
            },
            fail: err => {
              wx.hideLoading()
            }
          })
        }
      })

    },
    getPhoneNumber(e) {
      const that = this
      if (that.data.isFreeze) {
        wx.showToast({
          title: '账号异常',
          icon: 'error'
        })
        return
      }
      let errMsg = e.detail.errMsg
      if (errMsg === "getPhoneNumber:fail user deny") {
        wx.showToast({
          title: '请绑定手机号，以便我们为您提供后续服务。',
          icon: 'none',
          duration: 2000
        })

        api.wxRejectMobile({
          data: {},
          success: () => {
            console.log('wxRejectMobile')
          }
        })
        return
      }
      api.bindMobile({
        data: {
          type: 1,
          appid: "wxff3fc00494f4f0e3",
          encryptedData: e.detail.encryptedData, //获取到的加密数据
          iv: e.detail.iv, //获取到的iv数据
          forceBind: true
        },
        success: res => {
          if (res.code * 1 === 0) {
            that.login()
            // that.triggerEvent("closeModal")
          } else {
            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  title: res.msg,
                })
              },
            })
          }
        }
      })
    },
    commonOauthBaseinfo() {
      const that = this
      api.commonOauthBaseinfo({
        data: {},
        success: res => {
          if (res.code === 0) {
            if (res.data.status * 1 === 2) {
              wx.showToast({
                title: '账号异常，请更换账号后登录',
                icon: 'none'
              })
            } else {
              wx.setStorageSync('userInfo', res.data)
              wx.setStorageSync('mobile', res.data.mobile)
              that.triggerEvent("closeModal")
              app.globalData = {
                ...app.globalData,
                channel: res.data.channel
              }
            }
          }
        },
        fail: err => {
          console.log(err)
        }
      })
    },
    bindCheckBindMobile() {
      const that = this

      api.bindCheckBindMobile({
        data: {},
        success: res => {
          console.log(res.data)
          if (res.data.bind) {
            that.commonOauthBaseinfo()
          }
          this.setData({
            bindMobile: res.data.bind
          })
          wx.setStorageSync('bindMobile', res.data.bind)
        }
      })
    },
    messageCompanyData(channel) {
      customerApi.messageCompany({
        data: {
          fromWhere: channel
        },
      })
    },
    jump(e) {
      const {url, type } = e.currentTarget.dataset;
      wx.navigateTo({
        url: `/pages/webview/index?url=${url}&type=${type}`,
      });
    }
  }
})